<?php

class Crud_ZendFormElement_File extends Zend_Form_Element_File
{
	public $isReallyRequired;
	
    /**
     * Receive the uploaded file
     *
     * @return boolean
     */
    public function receive()
    {
        if (!$this->getFileName()) {
        	return false;
        }
         
		$newName = $this->getUploadName();
    	$filter = new Zend_Filter_File_Rename($newName);
    	$this->addFilter($filter);
    	
    	$folder = substr($this->getHash('md5'), 0, 2);
    	$destination = $this->getDestination() . "/$folder";
    	
    	// Create directory when not exists
    	if (!is_dir($destination)) {
    		mkdir($destination, 0777);
    	}
    	
    	$this->setDestination($destination);

    	parent::receive();
    }
    
    /**
     * Return extension of uploaded file.
     * 
     * @return string
     */
    public function getExtension()
    {
    	$filename = $this->getFileName($this->getName(), false);
    	preg_match("/\.([a-z43]{1,4})$/i", $filename, $match);
    	if (!isset($match[1])) {
    		return null;
    	}
    	
    	return $match[1];
    }
    
    /**
     * Return name which file will renamed after upload.
     * 
     * @return string
     */
    public function getUploadName()
    {
    	$hash = $this->getHash('md5');
    	$extension = $this->getExtension();
    	return "$hash.$extension";
    }
    
    /**
     * Return true when file required in db.
     * 
     * @return boolean
     */
    public function isReallyRequired()
    {
    	return $this->isReallyRequired;
    }
}